跳到主要内容

160 相交链表

https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvpj16/

cost: 11m48s

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
auto pA = headA, pB = headB;
bool jumpA = false, jumpB = false;
while (1) {
if (pA == pB && pA != nullptr) {
return pA;
}

if (pA == nullptr) {
if (jumpA) {
return nullptr;
}
pA = headB;
jumpA = true;
} else {
pA = pA->next;
}

if (pB == nullptr) {
if (jumpB) {
return nullptr;
}
pB = headA;
jumpB = true;
} else {
pB = pB->next;
}
}
return nullptr;
}
};